package com.lagou.servlet;

import com.lagou.service.UserService;
import com.lagou.service.UserServiceImpl;
import com.lagou.entity.User;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "AdminLoginServlet", urlPatterns = "/adminLoginServlet")
public class AdminLoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 1、获取请求中用户名和密码信息并打印出来
        String userName = request.getParameter("userName");
        System.out.println("获取到的用户名为： "+userName);
        String password = request.getParameter("password");
        System.out.println("获取到的密码为： "+password);

        // 2、创建UserService类型的对象去实现数据的校验功能
        UserService userService = new UserServiceImpl();
        User user = userService.userLoginService(new User(userName,password));
        if(null == user){
            System.out.println("登录失败，用户名或密码错误！");
            request.setAttribute("error", "登录失败，用户名或密码错误");
            //实现服务器跳转 共享request和 response 对象
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("index.jsp");
            requestDispatcher.forward(request, response);
        } else {
            System.out.println("登录成功， 欢迎使用!");
            //存储用户名信息
            request.getSession().setAttribute("user", user);
            //实现7天内免登录
            //创建Cookie对象用于存储用户名信息
            Cookie userNameCookie = new Cookie("userName", userName);
            //设置cookie一周内有效 一小时3600s 一天24小时、 一周7天，可以用3分钟进行测试
            userNameCookie.setMaxAge(3600*24*7);
            //将cookie信息返回给客户端浏览器
            response.addCookie(userNameCookie);
            //通过客户端跳转的方式 实现主页面的访问
            response.sendRedirect("mainPage.jsp");

        }




    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}